const onInstalled = async ({ reason }) => {
  if (reason !== "install" && reason !== "update") {
    return;
  }
  const defaultRulesets = chrome.runtime.getManifest()?.declarative_net_request.rule_resources;
  const localRulesets = await chrome.storage.local.get({
    rulesets: [],
  });
  const rulesets = defaultRulesets.map((ruleset) => {
    const localRuleset = localRulesets[ruleset.id];
    const enabled = localRuleset?.enabled ?? ruleset.enabled;
    return {
      id: ruleset.id,
      enabled: enabled,
    };
  });
  chrome.storage.local.set({ rulesets });
};

chrome.runtime.onInstalled.addListener((details) => {
  onInstalled(details).catch(console.error);
});

// chrome.action.onClicked.addListener(() => {
//   chrome.runtime.openOptionsPage();
// });

chrome.storage.onChanged.addListener(async (changes, namespace) => {
  if (namespace !== "local" || !changes.hasOwnProperty("rulesets")) {
    return;
  }
  const currentEnabledRulesets = await chrome.declarativeNetRequest.getEnabledRulesets().then((ids) => new Set(ids));
  const options = (changes.rulesets?.newValue ?? []).reduce(
    (options, ruleset) => {
      if (ruleset.enabled && !currentEnabledRulesets.has(ruleset.id)) {
        options.enableRulesetIds.push(ruleset.id);
      }
      if (!ruleset.enabled && currentEnabledRulesets.has(ruleset.id)) {
        options.disableRulesetIds.push(ruleset.id);
      }
      return options;
    },
    { disableRulesetIds: [], enableRulesetIds: [] }
  );
  if (options.disableRulesetIds.length > 0 || options.enableRulesetIds.length > 0) {
    await chrome.declarativeNetRequest.updateEnabledRulesets(options);
  }
});
